
package com.wwy.monitor.controller;

import com.wwy.monitor.common.MessageException;
import com.wwy.monitor.common.PageResult;
import com.wwy.monitor.common.ResponseEnum;
import com.wwy.monitor.common.ServiceResponse;
import com.wwy.monitor.model.enumeration.DeleteEnum;
import com.wwy.monitor.model.enumeration.EnableStatusEnum;
import com.wwy.monitor.model.tddl.dto.MonitorIpDTO;
import com.wwy.monitor.model.tddl.query.MonitorIpQuery;
import com.wwy.monitor.model.vo.IpBatchVO;
import com.wwy.monitor.service.MonitorIpService;
import com.wwy.monitor.util.UserUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

@RestController
@RequestMapping(value = "/api/monitorIp")
public class MonitorIpController {
    @Resource(name = "monitorIpService")
    private MonitorIpService monitorIpService;

    /**
     * 分页获取
     *
     * @return
     */
    @GetMapping("/page")
    @ResponseBody
    private ServiceResponse page(Integer pageNum, Integer pageSize, Long appId) {
        if (pageNum == null || pageSize == null) {
            return ServiceResponse.paramIllegal("分页参数不能为空");
        }
        MonitorIpQuery query = new MonitorIpQuery();
        if (appId != null) {
            query.setAppId(appId);
        }
        Integer offset = (pageNum - 1) * pageSize;
        query.setOffset(offset);
        query.setSize(pageSize);
        query.setIsDelete(DeleteEnum.NOT_DELETE.getValue());
        PageResult pageResult = new PageResult();
        pageResult.setCurrentPage(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotalCount(monitorIpService.count(query));
        pageResult.setDatas(monitorIpService.queryMonitorIp(query));
        pageResult.getPages();
        return ServiceResponse.success(pageResult);
    }

    @GetMapping("/appIps")
    private ServiceResponse appIps(Long appId, String ip) {
        if (null == appId || appId <= 0) {
            throw new MessageException("非法id");
        }
        return ServiceResponse.success(monitorIpService.getAllIpByAppId(appId, ip));
    }

    @PostMapping("/add")
    @ResponseBody
    private ServiceResponse add(HttpServletRequest request, @RequestBody MonitorIpDTO dto)
            throws IOException, ServletException {
        // 参数校验
        if (!checkParameter(dto)) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), ResponseEnum.PARAM_EMPTY.getDesc());
        }
        // ipv4 ipv6校验
        String empId = UserUtils.getBucEmpId(request);
        dto.setCreateUser(empId);
        dto.setIsDelete(DeleteEnum.NOT_DELETE.getValue());
        boolean flag = monitorIpService.insert(dto);
        if (!flag) {
            return ServiceResponse.fail(ResponseEnum.SAVE_EXCEPTION.getCode(), ResponseEnum.SAVE_EXCEPTION.getDesc());
        }
        return ServiceResponse.success(ResponseEnum.SUCCESS.getDesc());
    }

    @PostMapping("/update")
    @ResponseBody
    private ServiceResponse update(HttpServletRequest request, @RequestBody MonitorIpDTO dto)
            throws IOException, ServletException {
        // 参数校验
        if (!checkParameter(dto)) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), ResponseEnum.PARAM_EMPTY.getDesc());
        }
        String empId = UserUtils.getBucEmpId(request);
        dto.setUpdateUser(empId);
        boolean flag = monitorIpService.updateById(dto);
        if (!flag) {
            return ServiceResponse.fail(ResponseEnum.UPDATE_EXCEPTION.getCode(), ResponseEnum.UPDATE_EXCEPTION.getDesc());
        }
        return ServiceResponse.success(ResponseEnum.SUCCESS.getDesc());
    }

    /**
     * 参数校验
     *
     * @param dto
     * @return
     */
    private boolean checkParameter(MonitorIpDTO dto) {
        return (dto != null && dto.getAppId() != null && StringUtils.isNotBlank(dto.getIp()) && dto.getEnv() != null);
    }

    @PostMapping("/delete")
    @ResponseBody
    private ServiceResponse delete(Long id) {
        if (id == null) {
            return ServiceResponse.fail(ResponseEnum.PARAM_EMPTY.getCode(), ResponseEnum.PARAM_EMPTY.getDesc());
        }
        boolean flag = monitorIpService.deleteById(id);
        if (!flag) {
            return ServiceResponse.fail(ResponseEnum.DELETE_EXCEPTION.getCode(), ResponseEnum.DELETE_EXCEPTION.getDesc());
        }
        return ServiceResponse.success(ResponseEnum.SUCCESS.getDesc());
    }

    @PostMapping("/deleteBatch")
    @ResponseBody
    private ServiceResponse deleteBatch(@RequestBody IpBatchVO vo) {
        boolean flag = monitorIpService.deleteByIds(vo.getIds());
        if (!flag) {
            return ServiceResponse.fail(ResponseEnum.DELETE_EXCEPTION.getCode(), ResponseEnum.DELETE_EXCEPTION.getDesc());
        }
        return ServiceResponse.success(ResponseEnum.SUCCESS.getDesc());
    }

    /**
     * 批量添加ip
     *
     * @param request
     * @param vo
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @PostMapping("/addBatch")
    @ResponseBody
    private ServiceResponse addBatch(HttpServletRequest request, @RequestBody IpBatchVO vo)
            throws IOException, ServletException {
        // 参数校验
        boolean checkFlag = (vo != null && vo.getAppId() != null && StringUtils.isNotBlank(vo.getIps())
                && vo.getEnv() != null);
        if (!checkFlag) {
            return ServiceResponse.paramIllegal("参数ä¸å¨");
        }
        String[] ipArray = vo.getIps().split(",");
        if (ArrayUtils.isEmpty(ipArray)) {
            return ServiceResponse.paramIllegal("æ ææip");
        }
        String empId = UserUtils.getBucEmpId(request);
        List<MonitorIpDTO> monitorIpDTOList = new ArrayList<>();
        Stream.of(ipArray).forEach((ip) -> {
            MonitorIpDTO dto = new MonitorIpDTO();
            dto.setIp(ip);
            dto.setAppId(vo.getAppId());
            dto.setEnv(vo.getEnv());
            dto.setStatus(EnableStatusEnum.ENABLE.getValue());
            dto.setIsDelete(DeleteEnum.NOT_DELETE.getValue());
            dto.setCreateTime(new Date());
            dto.setUpdateTime(new Date());
            dto.setCreateUser(empId);
            dto.setCreateUser(empId);
            dto.setUpdateUser(empId);
            monitorIpDTOList.add(dto);
        });
        boolean flag = false;
        if (monitorIpDTOList.size() > 0) {
            flag = monitorIpService.insertBatch(monitorIpDTOList);
        }
        if (!flag) {
            return ServiceResponse.fail(ResponseEnum.SAVE_EXCEPTION.getCode(), ResponseEnum.SAVE_EXCEPTION.getDesc());
        }
        return ServiceResponse.success(ResponseEnum.SUCCESS.getDesc());
    }

    @GetMapping("/getServerIps")
    private ServiceResponse getServerIps(String appName) {
        return ServiceResponse.success(monitorIpService.getServerIps(appName));
    }

    @GetMapping("/syncServerIp")
    private ServiceResponse syncServerIp(String appName) {
        return ServiceResponse.success(monitorIpService.syncServerIp(appName));
    }
}